package com.mohan.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mohan.bean.ManagerInfo;
import com.mohan.bean.UserListInfo;
import com.mohan.bean.UserPageInfo;
import com.mohan.common.LoginToken;
import com.mohan.pojo.User;
import com.mohan.rep.ManageLoginRep;
import com.mohan.rep.UserPageRep;
import com.mohan.req.AddUserReq;
import com.mohan.req.ManagerLoginReq;
import com.mohan.req.UpdateUserReq;
import com.mohan.req.UserInfoReq;
import com.mohan.req.UserListReq;
import com.mohan.service.UserService;
import com.mohan.test.TestLogin;
import com.mohan.test.UserInfo;
import com.mohan.tool.Base64CC;
import com.mohan.tool.UserIdBuild;
import com.mohan.tool.UserMap;
import com.mohan.util.BetweenUtil;
import com.mohan.util.DetailUserInfo;
import com.mohan.util.PageData;
import com.mohan.util.ResponseUtil;
import com.mohan.util.TokenUserInfo;
import com.sun.corba.se.impl.oa.poa.ActiveObjectMap.Key;

@Controller
@RequestMapping(value = "/V1/manager")
public class ManagerController extends BaseController{

	@Resource
	private UserService userService;

	@RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object login(HttpServletRequest request,@RequestBody Map<String, Object> parmMap) {
		PageData pData = new PageData(parmMap);
		ResponseUtil repUtil = new ResponseUtil();
		try {
			if (validataParms(new String[]{"userId","userPwd"}, pData)) {
				User user = new User();
				user.setUserId(pData.getString("userId"));
				user.setUserPwd(pData.getString("userPwd"));
				User userNew = userService.getUserByUserIdAndUserPwd(user);
				if (userNew == null) {
					repUtil.failed(2003, "不存在该用户!");
				} else {
					if(userNew.getUserStatus() == 2){
						//用户被禁用
						repUtil.failed(2009, "用户被禁用");
					}else{
						TokenUserInfo tokenUserInfo = new TokenUserInfo();
						tokenUserInfo.setRole(userNew.getRole());
						tokenUserInfo.setUserId(userNew.getUserId());
						tokenUserInfo.setUserStatus(userNew.getUserStatus());						
						if (userService.dealLogin(userNew.getUserId(), tokenUserInfo) == 0) {
							Map<String, Object> loginRep = new HashMap<String, Object>();	
							loginRep.put("role", userNew.getRole());
							loginRep.put("userStatus", userNew.getUserStatus());
							loginRep.put("token", UserMap.UserId2TokenMap.get(userNew.getUserId()).getToken());
							repUtil.defaultSucess(loginRep);
						} else {
							repUtil.failed(2002, "系统异常");
						}
					}
				}
			}else{
				repUtil.failed(2001, "参数异常");
			} 
		} catch (Exception e) {  
			// TODO: handle exception
			e.printStackTrace();
			repUtil.failed(2002, "系统异常");
		} finally{
			logger.debug("====================================end  post AppUser register ...");
		}
		
		return returnObject(pData, repUtil);
	}

	/**
	 * 后台管理登录,只有管理员账号能登录
	 * 
	 * @param mLoginReq
	 * @param request
	 * @return
	 */
//	@RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
//	@ResponseBody
//	public Object manageLogin(HttpServletRequest request, @RequestBody ManagerLoginReq mLoginReq) {
//		String repStr = null;
//		int errCode = 0;
//		ManageLoginRep mLoginRep = new ManageLoginRep();
//		/**
//		 * 判断上传的参数
//		 */
//		if (mLoginReq.getUserId() == null || mLoginReq.getUserPwd() == null) {
//			repStr = "参数上传错误!";
//			errCode = 2001;
//		} else {
//			/**
//			 * 获取参数,并进行Base64解码 userId,userPwd
//			 */
//			try {
//				String userId = Base64CC.decode(mLoginReq.getUserId());
//				String userPwd = Base64CC.decode(mLoginReq.getUserPwd());
//				/**
//				 * 通过用户ID和用户密码获取用户信息,如果能够获取带用户信息,说明用户存在,否则不存在
//				 */
//				User user = new User();
//				user.setUserId(userId);
//				user.setUserPwd(userPwd);
//				User userNew = userService.getUserByUserIdAndUserPwd(user);
//				if (userNew != null) {// 有一个用户匹配
//
//					TokenUserInfo tokenUserInfo = new TokenUserInfo();
//					tokenUserInfo.setRole(userNew.getRole());
//					tokenUserInfo.setUserId(userId);
//					tokenUserInfo.setUserStatus(userNew.getUserStatus());
//					tokenUserInfo.setUserType(userNew.getUserType());
//
//					/**
//					 * 回复的字符串数据要进行base64编码
//					 */
//					ManagerInfo managerInfo = new ManagerInfo();
//					managerInfo.setUserId(Base64CC.encode(userId));
//					managerInfo.setUserName(Base64CC.encode(userNew.getUserName()));
//					managerInfo.setUserPwd("");
//					managerInfo.setUserStatus(userNew.getUserStatus());
//					managerInfo.setRole(userNew.getRole());
//					managerInfo.setUserType(userNew.getUserType());
//					if (userService.dealLogin(userId, tokenUserInfo) == 0) {
//						mLoginRep.setUserId(Base64CC.encode(userId));
//						mLoginRep.setToken(Base64CC.encode(UserMap.UserId2TokenMap.get(userId).getToken()));
//						mLoginRep.setUser(managerInfo);
//					} else {
//						repStr = "token生成失败";
//						errCode = 2002;
//					}
//				}else {// 系统错误
//					repStr = "用户名或密码不对!";
//					errCode = 2003;
//				}
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				repStr = "Base64解码失败!";
//			}
//		}
//
//		/**
//		 * 判定返回
//		 */
//		if (repStr == null) {
//			ResponseUtil response = new ResponseUtil();
//			response.defaultSucess(mLoginRep);
//			return response;
//		} else {
//			System.out.println("repStr : " + repStr);
//			ResponseUtil response = new ResponseUtil();
//			/**
//			 * 对repStr进行base64编码
//			 */
//			try {
//				response.defaultFailed(errCode, Base64CC.encode(repStr));
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			return response;
//		}
//	}

	/**
	 * 通过后台添加用户
	 * 
	 * @param request
	 * @return
	 */
//	@RequestMapping("/addUser")
//	@ResponseBody
//	public Object addUser(HttpServletRequest request, @RequestBody AddUserReq userReq) {
//		String repStr = null;
//		String newUserId = null;
//		int errCode = 0;
//		/**
//		 * 判断上传的参数
//		 */
//		if (userReq.getUserId() == null || userReq.getToken() == null || userReq.getUser() == null) {
//			repStr = "参数上传错误!";
//			errCode = 2001;
//		} else {
//			/**
//			 * 获取参数,并进行Base64解码 userId,token,newUserInfo
//			 */
//			try {
//				userReq.setUserId(Base64CC.decode(userReq.getUserId()));
//				userReq.setToken(Base64CC.decode(userReq.getToken()));
//
//				/**
//				 * 登录验证
//				 */
//				int loginConfirm = LoginToken.loginConfirm(userReq.getUserId(), userReq.getToken());
//				if (loginConfirm == 0) {
//					/**
//					 * 验证成功 获取注册新用户的信息
//					 */
//					if (userReq.getUser().getUserName() != null) {
//						userReq.getUser().setUserName(Base64CC.decode(userReq.getUser().getUserName()));
//					} else {
//						repStr = "请添加用户名!";
//						errCode = 2006;
//					}
//					if (userReq.getUser().getUserPwd() != null) {
//						userReq.getUser().setUserPwd(Base64CC.decode(userReq.getUser().getUserPwd()));
//					} else {
//						repStr = "请添加用户密码!";
//						errCode = 2007;
//					}
//					if (userReq.getUser().getRole() != 0) {
//						if (!(userReq.getUser().getRole() == 2 || userReq.getUser().getRole() == 3))
//							repStr = "只能添加管理员和普通用户,不能添加超级管理员!";
//						errCode = 2008;
//					} else {
//						repStr = "请添加用户角色!";
//						errCode = 2009;
//					}
//					if (userReq.getUser().getUserType() != 0) {
//						if (!(userReq.getUser().getUserType() == 2))
//							repStr = "只能添加用户类别为非微信用户!";
//						errCode = 2010;
//					} else {
//						repStr = "请添加用户类别!";
//						errCode = 2011;
//					}
//
//					/**
//					 * 验证用户权限 不能注册成超级用户;超级用户可以添加管理员和普通用户;管理员可以添加普通用户;普通用户没有添加权限
//					 */
//					if (repStr == null) {
//						if (userReq.getUser().getRole() != 1 && userReq.getUser().getRole() > UserMap.UserId2TokenMap
//								.get(userReq.getUserId()).getRole()) {
//							User user = new User();
//							/**
//							 * 生成userId
//							 */
//							newUserId = UserIdBuild.buildUserId();
//							/**
//							 * 查看userId是否已经存在于数据库
//							 * 这里没有处理,如果循环五次仍然是重复userId,一般情况是不可能的
//							 */
//							try {
//								for (int i = 0; i < 5; i++) {
//									Integer userIdSize = userService.userIdIsExist(newUserId);
//									System.out.println("userIdSize = " + userIdSize);
//									if (userIdSize == null) {
//										// userID可用
//										if (newUserId != null) {
//											user.setUserId(newUserId);
//											user.setUserName(userReq.getUser().getUserName());
//											user.setUserPwd(userReq.getUser().getUserPwd());
//											user.setUserType(userReq.getUser().getUserType());
//											user.setRole(userReq.getUser().getRole());
//											user.setOpenId("notWx");// 非微信用户默认
//											user.setUserStatus(1);
//											try {
//												userService.insertOneUser(user);
//											} catch (Exception e) {
//												// TODO Auto-generated catch
//												// block
//												e.printStackTrace();
//												repStr = "用户信息插入数据库失败!";
//												errCode = 2012;
//											}
//										} else {
//											repStr = "生成userId失败!";
//											errCode = 2013;
//										}
//										break;
//									} else {
//										/**
//										 * 再次生成userId
//										 */
//										newUserId = UserIdBuild.buildUserId();
//									}
//								}
//							} catch (Exception e1) {
//								// TODO Auto-generated catch block
//								e1.printStackTrace();
//								repStr = "数据库userId查重失败!";
//								errCode = 2014;
//							}
//						} else {
//							repStr = "权限不够!";
//							errCode = 2015;
//						}
//					}
//
//				} else if (loginConfirm == -1) {
//					repStr = "请先登录!";
//					errCode = 2016;
//				} else if (loginConfirm == -2) {
//					repStr = "账号异常!";
//					errCode = 2017;
//				} else {
//					repStr = "验证码过期,请重新登录!";
//					errCode = 2018;
//				}
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				repStr = "Base64解码失败!";
//				errCode = 2019;
//			}
//		}
//
//		/**
//		 * 判定返回,并对返回数据进行Base64编码
//		 */
//		String encodeRepStr = null;
//		if (repStr == null) {
//			try {
//				userReq.getUser().setUserId(Base64CC.encode(newUserId));
//				userReq.getUser().setUserName(Base64CC.encode(userReq.getUser().getUserName()));
//				userReq.getUser().setUserPwd("");
//				userReq.getUser().setUserStatus(1);
//			} catch (UnsupportedEncodingException e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//				repStr = "Base64编码失败!";
//			}
//		} else {
//			/**
//			 * 对repStr进行base64编码
//			 */
//			try {
//				encodeRepStr = Base64CC.encode(repStr);
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//
//		ResponseUtil response = new ResponseUtil();
//
//		if (repStr == null) {
//			response.defaultSucess(userReq.getUser());
//			return response;
//		} else {
//			System.out.println("repStr" + repStr);
//			response.defaultFailed(errCode, encodeRepStr);
//			return response;
//		}
//	}

	/**
	 * 分页获取用户列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/userList")
	@ResponseBody
	public Object getUserList(HttpServletRequest request, @RequestBody Map<String, Object> parmMap) {
		PageData pData = new PageData(parmMap);
		ResponseUtil repUtil = new ResponseUtil();
		try {
			if (validataParms(new String[]{"userId","token","role","queryPage","eachPageSize"}, pData)) {
				//登录验证
				int loginConfirm = LoginToken.loginConfirm(pData.getString("userId"), pData.getString("token"));
				if (loginConfirm == 0) {
					if (UserMap.UserId2TokenMap.get(pData.getString("userId")).getRole() == 1) {
						BetweenUtil role = new BetweenUtil();
						if (pData.getInt("role") == 1) {
							role.setStart(pData.getInt("role"));
							role.setEnd(4);
						}else {
							role.setStart(pData.getInt("role"));
							role.setEnd(pData.getInt("role"));
						}
						
						Integer roleSize = userService.getRecordSizeByRole(role);
						if (roleSize == null) {
							//数据为0
							UserPageRep uPageRep = new UserPageRep();
							uPageRep.setTotalRecord(0);
							repUtil.defaultSucess(uPageRep);
						} else {
							int totalRecord = roleSize.intValue();
							//int pageSize = (int) Math.ceil(totalRecord/(pData.getInt("eachPageSize") * 1.0));
							int start = (pData.getInt("queryPage") - 1)*pData.getInt("eachPageSize");
							role.setBegin(start);
							role.setEach(pData.getInt("eachPageSize"));						
							List<PageData> users = userService.getRecordByRole(role);
							UserPageRep uPageRep = new UserPageRep();
							uPageRep.setTotalRecord(totalRecord);
							uPageRep.setUsers(users);
							repUtil.defaultSucess(uPageRep);
						}
					} else {
						BetweenUtil role = new BetweenUtil();
						if (pData.getInt("role") == 1) {
							role.setStart(2);
							role.setEnd(4);
						}else {
							role.setStart(pData.getInt("role"));
							role.setEnd(pData.getInt("role"));
						}
						
						Integer roleSize = userService.getRecordSizeByRole(role);
						if (roleSize == null) {
							//数据为0
							UserPageRep uPageRep = new UserPageRep();
							uPageRep.setTotalRecord(0);
							repUtil.defaultSucess(uPageRep);
						} else {
							int totalRecord = roleSize.intValue();
							int pageSize = (int) Math.ceil(totalRecord/(pData.getInt("eachPageSize") * 1.0));
							int start = (pData.getInt("queryPage") - 1)*pData.getInt("eachPageSize");
							role.setBegin(start);
							role.setEach(pageSize);						
							List<PageData> users = userService.getRecordByRole(role);
							UserPageRep uPageRep = new UserPageRep();
							uPageRep.setTotalRecord(totalRecord);
							uPageRep.setUsers(users);
							repUtil.defaultSucess(uPageRep);
						}
					}
				} else if (loginConfirm == -1) {
					repUtil.failed(2004, "未登录");
				} else if (loginConfirm == -2) {
					repUtil.failed(2005, "账号异常");
				} else if (loginConfirm == -3) {
					repUtil.failed(2006, "验证码过期");
				}else if (loginConfirm == -4) {
					repUtil.failed(2007, "权限不够");
				}else{
					repUtil.failed(2002, "系统异常");
				}
			}else{
				repUtil.failed(2001, "参数异常");
			} 
		} catch (Exception e) {  
			// TODO: handle exception
			e.printStackTrace();
			repUtil.failed(2002, "系统异常");
		} finally{
			logger.debug("====================================end  post AppUser register ...");
		}
		
		return returnObject(pData, repUtil);
	}
//	public Object getUserList(HttpServletRequest request, @RequestBody UserListReq uListReq) {
//		String repStr = null;
//		int errCode = 0;
//		List<UserPageInfo> uPageInfos = new ArrayList<UserPageInfo>();
//		if (uListReq.getUserId() == null || uListReq.getToken() == null || uListReq.getListCon() == null) {
//			repStr = "参数上传错误!";
//			errCode = 2001;
//		} else {
//			try {
//				/**
//				 * 解码参数
//				 */
//				uListReq.setUserId(Base64CC.decode(uListReq.getUserId()));
//				uListReq.setToken(Base64CC.decode(uListReq.getToken()));
//				/**
//				 * 登录校验
//				 */
//				int loginConfirm = LoginToken.loginConfirm(uListReq.getUserId(), uListReq.getToken());
//				if (loginConfirm == 0) {
//					// 校验成功
//					/**
//					 * 权限验证
//					 */
//					if (uListReq.getListCon().getRole() != -1) {
//						if (uListReq.getListCon().getRole() > 1 && uListReq.getListCon().getRole() < 4 && uListReq
//								.getListCon().getRole() > UserMap.UserId2TokenMap.get(uListReq.getUserId()).getRole()) {
//							/**
//							 * 如果没有带总的记录数则从数据库获取总的记录数
//							 */
//							if (uListReq.getListCon().getTotalRecord() < 1) {
//
//								Integer roleSize = userService.getRecordSizeByRole(uListReq.getListCon().getRole());
//								if (roleSize == null) {
//									uListReq.getListCon().setTotalRecord(0);
//								} else {
//									uListReq.getListCon().setTotalRecord(roleSize.intValue());
//								}
//								if (uListReq.getListCon().getEachPageSize() < 1) {
//									uListReq.getListCon().setEachPageSize(20);
//								}
//								if (uListReq.getListCon().getQueryPage() < 1) {
//									uListReq.getListCon().setQueryPage(1);
//								}
//								int pageSize = (int) Math.ceil(uListReq.getListCon().getTotalRecord()
//										/ (uListReq.getListCon().getEachPageSize() * 1.0));
//								uListReq.getListCon().setTotalPages(pageSize);
//								if (uListReq.getListCon().getQueryPage() > uListReq.getListCon().getTotalPages()) {
//									uListReq.getListCon().setQueryPage(pageSize);
//								}
//								uListReq.getListCon().setStart((uListReq.getListCon().getQueryPage() - 1)
//										* uListReq.getListCon().getEachPageSize());
//								/**
//								 * 从数据库查询
//								 */
//								List<User> users = userService.getRecordSizeByRole(uListReq.getListCon());
//								if (!users.isEmpty()) {
//
//									for (User user : users) {
//										UserPageInfo uPageInfo = new UserPageInfo();
//										uPageInfo.setRole(user.getRole());
//										uPageInfo.setUserId(Base64CC.encode(user.getUserId()));
//										uPageInfo.setUserName(Base64CC.encode(user.getUserName()));
//										uPageInfo.setUserStatus(user.getUserStatus());
//										uPageInfo.setUserType(user.getUserType());
//										uPageInfos.add(uPageInfo);
//									}
//									uListReq.getListCon().setuPageInfos(uPageInfos);
//								}
//							} else {
//								/**
//								 * 如果带了总的记录数
//								 */
//								if (uListReq.getListCon().getQueryPage() > 0
//										&& uListReq.getListCon().getQueryPage() < uListReq.getListCon().getTotalPages()
//										&& uListReq.getListCon().getEachPageSize() > 0) {
//									uListReq.getListCon().setStart((uListReq.getListCon().getQueryPage() - 1)
//											* uListReq.getListCon().getEachPageSize());
//									/**
//									 * 从数据库查询
//									 */
//									List<User> users = userService.getRecordSizeByRole(uListReq.getListCon());
//									if (!users.isEmpty()) {
//
//										for (User user : users) {
//											UserPageInfo uPageInfo = new UserPageInfo();
//											uPageInfo.setRole(user.getRole());
//											uPageInfo.setUserId(Base64CC.encode(user.getUserId()));
//											uPageInfo.setUserName(Base64CC.encode(user.getUserName()));
//											uPageInfo.setUserStatus(user.getUserStatus());
//											uPageInfo.setUserType(user.getUserType());
//											uPageInfos.add(uPageInfo);
//										}
//										uListReq.getListCon().setuPageInfos(uPageInfos);
//									}
//								} else {
//									repStr = "参数错误!";
//									errCode = 2001;
//								}
//							}
//						} else {
//							repStr = "用户权限不够!";
//							errCode = 2015;
//						}
//					} else {
//						repStr = "请添加要查询的用户角色!";
//						errCode = 2020;
//					}
//
//				} else if (loginConfirm == -1) {
//					repStr = "请先登录!";
//					errCode = 2016;
//				} else if (loginConfirm == -2) {
//					repStr = "账号异常!";
//					errCode = 2017;
//				} else {
//					repStr = "验证码过期,请重新登录!";
//					errCode = 2018;
//				}
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				repStr = "Base64解码参数失败!";
//				errCode = 2019;
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				repStr = "数据库查询失败!";
//				errCode = 2021;
//			}
//		}
//
//		/**
//		 * 判定返回,并对返回数据进行Base64编码
//		 */
//		String encodeRepStr = null;
//		if (repStr != null) {
//			try {
//				encodeRepStr = Base64CC.encode(repStr);
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//
//		ResponseUtil response = new ResponseUtil();
//		if (repStr == null) {
//			response.defaultSucess(uListReq.getListCon());
//			return response;
//		} else {
//			System.out.println("repStr" + repStr);
//			response.defaultFailed(errCode, encodeRepStr);
//			return response;
//		}
//	}

	/**
	 * 根据userId获取用户信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/userInfo")
	@ResponseBody
	public Object getUserByUserId(HttpServletRequest request, @RequestBody UserInfoReq uInfoReq) {
		String repStr = null;
		int errCode = 0;
		DetailUserInfo uInfo = new DetailUserInfo();
		/**
		 * 判断上传参数
		 */
		if (uInfoReq.getUserId() == null || uInfoReq.getToken() == null || uInfoReq.getTargetUserId() == null) {
			repStr = "参数上传错误!";
			errCode = 2001;
		} else {
			/**
			 * Base64解码参数
			 */
			try {
				uInfoReq.setUserId(Base64CC.decode(uInfoReq.getUserId()));
				uInfoReq.setToken(Base64CC.decode(uInfoReq.getToken()));
				uInfoReq.setTargetUserId(Base64CC.decode(uInfoReq.getTargetUserId()));
				/**
				 * 登录验证
				 */
				int loginConfirm = LoginToken.loginConfirm(uInfoReq.getUserId(), uInfoReq.getToken());
				if (loginConfirm == 0) {
					/**
					 * 数据库查询信息
					 */
					User user = userService.getUserByUserId(uInfoReq.getTargetUserId());
					if (user != null) {

						/**
						 * 权限验证,一个是大权限查看小权限,一个是查看自己的
						 */
						if (UserMap.UserId2TokenMap.get(uInfoReq.getUserId()).getRole() == 1
								|| UserMap.UserId2TokenMap.get(uInfoReq.getUserId()).getRole() == 2) {
							// 管理员
							uInfo.setAvatarUrl(Base64CC.encode(user.getAvatarUrl()));
							uInfo.setCity(Base64CC.encode(user.getCity()));
							uInfo.setCountry(Base64CC.encode(user.getCountry()));
							uInfo.setGender(Base64CC.encode(user.getGender()));
							uInfo.setLanguage(Base64CC.encode(user.getLanguage()));
							uInfo.setNickName(Base64CC.encode(user.getNickName()));
							uInfo.setOpenId(Base64CC.encode(user.getOpenId()));
							uInfo.setPhoneNum(Base64CC.encode(user.getPhoneNum()));
							uInfo.setProvince(Base64CC.encode(user.getProvince()));
							uInfo.setRole(user.getRole());
							uInfo.setUserId(Base64CC.encode(user.getUserId()));
							uInfo.setUserName(Base64CC.encode(user.getUserName()));
							uInfo.setUserStatus(user.getUserStatus());
							uInfo.setUserType(user.getUserType());
						} else if (uInfoReq.getUserId().equals(uInfoReq.getTargetUserId())) {
							// 自己
							uInfo.setAvatarUrl(Base64CC.encode(user.getAvatarUrl()));
							uInfo.setCity(Base64CC.encode(user.getCity()));
							uInfo.setCountry(Base64CC.encode(user.getCountry()));
							uInfo.setGender(Base64CC.encode(user.getGender()));
							uInfo.setLanguage(Base64CC.encode(user.getLanguage()));
							uInfo.setNickName(Base64CC.encode(user.getNickName()));
							uInfo.setPhoneNum(Base64CC.encode(user.getPhoneNum()));
							uInfo.setProvince(Base64CC.encode(user.getProvince()));
							uInfo.setUserId(Base64CC.encode(user.getUserId()));
							uInfo.setUserName(Base64CC.encode(user.getUserName()));
						} else {
							// 其他人
							uInfo.setAvatarUrl(Base64CC.encode(user.getAvatarUrl()));
							uInfo.setNickName(Base64CC.encode(user.getNickName()));
							uInfo.setUserId(Base64CC.encode(user.getUserId()));
							uInfo.setGender(Base64CC.encode(user.getGender()));
						}
					} else {
						repStr = "查询的用户不存在!";
						errCode = 2022;
					}
				} else if (loginConfirm == -1) {
					repStr = "请先登录!";
					errCode = 2016;
				} else if (loginConfirm == -2) {
					repStr = "账号异常!";
					errCode = 2017;
				} else {
					repStr = "验证码过期,请重新登录!";
					errCode = 2018;
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				repStr = "Base64解码上传参数失败!";
				errCode = 2019;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				repStr = "数据库查询失败!";
				errCode = 2021;
			}
		}

		/**
		 * 判定返回,并对返回数据进行Base64编码
		 */
		String encodeRepStr = null;
		if (repStr != null) {
			try {
				encodeRepStr = Base64CC.encode(repStr);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		ResponseUtil response = new ResponseUtil();
		if (repStr == null) {
			response.defaultSucess(uInfo);
			return response;
		} else {
			System.out.println("repStr" + repStr);
			response.defaultFailed(errCode, encodeRepStr);
			return response;
		}
	}

	/**
	 * 根据userId修改其他用户信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateUser")
	@ResponseBody
	public Object updateUserInfo(HttpServletRequest request, @RequestBody UpdateUserReq upUserReq) {
		String repStr = null;
		int errCode = 0;
		/**
		 * 判断上传参数
		 */
		if (upUserReq.getUserId() == null || upUserReq.getToken() == null || upUserReq.getUser() == null) {
			repStr = "参数上传错误!";
			errCode = 2001;
		} else {
			try {
				upUserReq.setUserId(Base64CC.decode(upUserReq.getUserId()));
				upUserReq.setToken(Base64CC.decode(upUserReq.getToken()));
				/**
				 * 登录验证
				 */
				int loginConfirm = LoginToken.loginConfirm(upUserReq.getUserId(), upUserReq.getToken());
				if (loginConfirm == 0) {
					// 验证成功

					/**
					 * Base64解码上传的参数
					 */

					if (upUserReq.getUser().getUserId() != null) {
						upUserReq.getUser().setUserId(Base64CC.decode(upUserReq.getUser().getUserId()));

						User user = userService.getUserByUserId(upUserReq.getUser().getUserId());
						if (user != null) {
							User selectUser = user;
							if (upUserReq.getUser().getRole() > 0 && upUserReq.getUser().getRole() < 4) {
								/**
								 * 需要修改用户角色
								 */
								if (UserMap.UserId2TokenMap.get(upUserReq.getUserId()).getRole() == 1) {
									/**
									 * 只有超级管理员可以修改userName,userPwd,role,userStatus,userType
									 */
									selectUser.setRole(upUserReq.getUser().getRole());

									if (upUserReq.getUser().getUserName() != null) {
										selectUser.setUserName(Base64CC.decode(upUserReq.getUser().getUserName()));
									}
									if (upUserReq.getUser().getUserPwd() != null) {
										selectUser.setUserPwd(Base64CC.decode(upUserReq.getUser().getUserPwd()));
									}
									if (upUserReq.getUser().getUserStatus() > 0
											&& upUserReq.getUser().getUserStatus() < 4) {
										selectUser.setUserStatus(upUserReq.getUser().getUserStatus());
									}
									if (upUserReq.getUser().getUserType() > 0
											&& upUserReq.getUser().getUserType() < 3) {
										selectUser.setUserType(upUserReq.getUser().getUserType());
									}
									userService.updateUserInfoByUserId(selectUser);
								} else if (upUserReq.getUserId().equals(upUserReq.getUser().getUserId())) {
									/**
									 * 用户自己修改自己信息,只能修改用户名和用户密码
									 */
									if (upUserReq.getUser().getUserName() != null) {
										selectUser.setUserName(Base64CC.decode(upUserReq.getUser().getUserName()));
									}
									if (upUserReq.getUser().getUserPwd() != null) {
										selectUser.setUserPwd(Base64CC.decode(upUserReq.getUser().getUserPwd()));
									}
									userService.updateUserInfoByUserId(selectUser);
								} else {
									repStr = "权限不够!";
									errCode = 2015;
								}
							} else {
								if (UserMap.UserId2TokenMap.get(upUserReq.getUserId()).getRole() == 1) {
									/**
									 * 只有超级管理员可以修改userName,userPwd,role,userStatus,userType
									 */
									if (upUserReq.getUser().getUserName() != null) {
										selectUser.setUserName(Base64CC.decode(upUserReq.getUser().getUserName()));
									}
									if (upUserReq.getUser().getUserPwd() != null) {
										selectUser.setUserPwd(Base64CC.decode(upUserReq.getUser().getUserPwd()));
									}
									if (upUserReq.getUser().getUserStatus() > 0
											&& upUserReq.getUser().getUserStatus() < 4) {
										selectUser.setUserStatus(upUserReq.getUser().getUserStatus());
									}
									if (upUserReq.getUser().getUserType() > 0
											&& upUserReq.getUser().getUserType() < 3) {
										selectUser.setUserType(upUserReq.getUser().getUserType());
									}
									userService.updateUserInfoByUserId(selectUser);
								} else if (upUserReq.getUserId().equals(upUserReq.getUser().getUserId())) {
									/**
									 * 用户自己修改自己信息,只能修改用户名和用户密码
									 */
									if (upUserReq.getUser().getUserName() != null) {
										selectUser.setUserName(Base64CC.decode(upUserReq.getUser().getUserName()));
									}
									if (upUserReq.getUser().getUserPwd() != null) {
										selectUser.setUserPwd(Base64CC.decode(upUserReq.getUser().getUserPwd()));
									}
									userService.updateUserInfoByUserId(selectUser);
								} else {
									repStr = "权限不够!";
									errCode = 2015;
								}
							}
						} else {
							repStr = "用户不存在!";
							errCode = 2022;
						}
					} else {
						repStr = "参数缺少要修改用户的用户id!";
						errCode = 2001;
					}
				} else if (loginConfirm == -1) {
					repStr = "请先登录!";
					errCode = 2016;
				} else if (loginConfirm == -2) {
					repStr = "账号异常!";
					errCode = 2017;
				} else {
					repStr = "验证码过期,请重新登录!";
					errCode = 2018;
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				repStr = "Base64解码上传参数失败!";
				errCode = 2019;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				repStr = "数据库操作失败!";
				errCode = 2021;
			}
		}

		/**
		 * 判定返回,并对返回数据进行Base64编码
		 */
		String encodeRepStr = null;
		if (repStr != null) {
			try {
				encodeRepStr = Base64CC.encode(repStr);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		ResponseUtil response = new ResponseUtil();
		if (repStr == null) {
			try {
				response.defaultSucess(Base64CC.encode("用户信息更改成功!"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return response;
		} else {
			System.out.println("repStr" + repStr);
			response.defaultFailed(errCode, encodeRepStr);
			return response;
		}
	}

	/**
	 * 根据userId获取其他用户信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteManager")
	@ResponseBody
	public Object delete(HttpServletRequest request,@RequestBody Map<String, Object> parmMap) {
		PageData pData = new PageData(parmMap);
		ResponseUtil repUtil = new ResponseUtil();
		try {
			
			if (validataParms(new String[]{"userId","token","targetUserId"}, pData)) {
				int loginConfirm = LoginToken.loginConfirm(pData.getString("userId"), pData.getString("token"));
				if (loginConfirm == 0) {
					if (UserMap.UserId2TokenMap.get(pData.getString("userId")).getRole() == 1) {
						//只有超级管理员能删除用户
						if (pData.getString("userId").equals(pData.getString("targetUserId"))) {
							repUtil.failed(2007, "权限不够");
						}else {
							userService.deleteUserByUserId(pData.getString("targetUserId"));
							repUtil.defaultSucess("删除用户成功");
						}
					} else {
						repUtil.failed(2007, "权限不够");
					}
				} else if (loginConfirm == -1) {
					repUtil.failed(2004, "未登录");
				} else if (loginConfirm == -2) {
					repUtil.failed(2005, "账号异常");
				} else if (loginConfirm == -3) {
					repUtil.failed(2006, "验证码过期");
				}else if (loginConfirm == -4) {
					repUtil.failed(2007, "权限不够");
				}else{
					repUtil.failed(2002, "系统异常");
				}
				
			}else{
				repUtil.failed(2001, "参数异常");
			} 
		} catch (Exception e) {  
			// TODO: handle exception
			e.printStackTrace();
			repUtil.failed(2002, "系统异常");
		} finally{
			logger.debug("====================================end  post AppUser register ...");
		}
		
		return returnObject(pData, repUtil);
	}
	
	@RequestMapping("/updateStatus")
	@ResponseBody
	public Object updateStatus(HttpServletRequest request,@RequestBody Map<String, Object> parmMap) {
		PageData pData = new PageData(parmMap);
		ResponseUtil repUtil = new ResponseUtil();
		try {
			
			if (validataParms(new String[]{"userId","token","targetUserId","userStatus"}, pData)) {
				int loginConfirm = LoginToken.loginConfirm(pData.getString("userId"), pData.getString("token"));
				if (loginConfirm == 0) {
					if (UserMap.UserId2TokenMap.get(pData.getString("userId")).getRole() < 3 ) {
						User targetUser = userService.getUserByUserId(pData.getString("targetUserId"));
						if (targetUser != null) {
							if (UserMap.UserId2TokenMap.get(pData.getString("userId")).getRole() < targetUser.getRole()) {
								targetUser.setUserStatus(pData.getInt("userStatus"));
								userService.updateUserStatusByUserId(targetUser);
								repUtil.defaultSucess("用户状态修改成功");
							} else {
								repUtil.failed(2007, "权限不够");
							}
						}else {
							repUtil.failed(2008, "目标用户不存在");
						}
					} else {
						repUtil.failed(2007, "权限不够");
					}
				} else if (loginConfirm == -1) {
					repUtil.failed(2004, "未登录");
				} else if (loginConfirm == -2) {
					repUtil.failed(2005, "账号异常");
				} else if (loginConfirm == -3) {
					repUtil.failed(2006, "验证码过期");
				}else if (loginConfirm == -4) {
					repUtil.failed(2007, "权限不够");
				}else{
					repUtil.failed(2002, "系统异常");
				}
				
			}else{
				repUtil.failed(2001, "参数异常");
			} 
		} catch (Exception e) {  
			// TODO: handle exception
			e.printStackTrace();
			repUtil.failed(2002, "系统异常");
		} finally{
			logger.debug("====================================end  post AppUser register ...");
		}
		
		return returnObject(pData, repUtil);
	}
	
//	public Object deleteUser(HttpServletRequest request, @RequestBody UserInfoReq deleteUserReq) {
//		String repStr = null;
//		int errCode = 0;
//		if (deleteUserReq.getUserId() == null || deleteUserReq.getToken() == null
//				|| deleteUserReq.getTargetUserId() == null) {
//			repStr = "参数上传错误!";
//			errCode = 2001;
//		} else {
//			try {
//				/**
//				 * base64解码
//				 */
//				deleteUserReq.setUserId(Base64CC.decode(deleteUserReq.getUserId()));
//				deleteUserReq.setToken(Base64CC.decode(deleteUserReq.getToken()));
//				deleteUserReq.setTargetUserId(Base64CC.decode(deleteUserReq.getTargetUserId()));
//				/**
//				 * 登录验证
//				 */
//				int loginConfirm = LoginToken.loginConfirm(deleteUserReq.getUserId(), deleteUserReq.getToken());
//				if (loginConfirm == 0) {
//					/**
//					 * 权限验证
//					 */
//					if (UserMap.UserId2TokenMap.get(deleteUserReq.getUserId()).getRole() == 1) {
//						if (deleteUserReq.getUserId().equals(deleteUserReq.getTargetUserId())) {
//							repStr = "无法删除自身!";
//							errCode = 2023;
//						} else {
//							User user = userService.getUserByUserId(deleteUserReq.getTargetUserId());
//							if (user != null) {
//
//								/**
//								 * 从数据库删除数据
//								 */
//								userService.deleteUserByUserId(deleteUserReq.getTargetUserId());
//
//							} else {
//								repStr = "要删除的用户不存在!";
//								errCode = 2022;
//							}
//						}
//
//					} else {
//						repStr = "非超级管理员,没有权限删除用户!";
//						errCode = 2024;
//					}
//				} else if (loginConfirm == -1) {
//					repStr = "请先登录!";
//					errCode = 2016;
//				} else if (loginConfirm == -2) {
//					repStr = "账号异常!";
//					errCode = 2017;
//				} else {
//					repStr = "验证码过期,请重新登录!";
//					errCode = 2018;
//				}
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				repStr = "Base64解码上传参数失败!";
//				errCode = 2019;
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				repStr = "数据库操作失败!";
//				errCode = 2021;
//			}
//		}
//
//		/**
//		 * 判定返回,并对返回数据进行Base64编码
//		 */
//		String encodeRepStr = null;
//		if (repStr != null) {
//			try {
//				encodeRepStr = Base64CC.encode(repStr);
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//
//		ResponseUtil response = new ResponseUtil();
//		if (repStr == null) {
//			try {
//				response.defaultSucess(Base64CC.encode("用户信息删除成功!"));
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			return response;
//		} else {
//			System.out.println("repStr" + repStr);
//			response.defaultFailed(errCode, encodeRepStr);
//			return response;
//		}
//	}
}
